/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ez2find.backing;

import com.ez2find.manager.PostManagerLocal;
import com.ez2find.manager.RegisterUserManagerLocal;
import com.ez2find.manager.SiteManagerLocal;
import com.ez2find.model.Post;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import com.ez2find.services.EmailLocal;
import com.ez2find.util.SessionContext;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.adrian.encrypt.Encrypter;

/**
 *
 * @author Owner
 */
public class RegisterUserBean {

    @EJB
    private RegisterUserManagerLocal ejbUserManager;
    @EJB
    private PostManagerLocal ejbPostManager;
    @EJB
    private SiteManagerLocal ejbSiteManager;
    @EJB
    private EmailLocal ejbEmail;
    private RegisterUser registerUser;
    private long defaultSiteId;
    private int numberOfPostings;
    private String email1;
    private String email2;
    private String pwd;
    private String pwd1;
    private String pwd2;
    private boolean registerOk;
    private boolean confirmationOk;
    private String emailSearch;
    private boolean linkRPOk;
    private boolean recoveryOk;
    private long siteId;

    public RegisterUser getOwner() {
        SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
        return sessionBean.getEjbSession().getOwner();
    }

    public List<Post> getPostsOwner() {
        return ejbPostManager.postingsUser(getOwner());
    }

    public RegisterUser getRegisterUser() {
        if (registerUser == null) {
            registerUser = new RegisterUser();
        }

        return registerUser;
    }

    public void setRegisterUser(RegisterUser registerUser) {
        this.registerUser = registerUser;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPwd1() {
        return pwd1;
    }

    public void setPwd1(String pwd1) {
        this.pwd1 = pwd1;
    }

    public String getPwd2() {
        return pwd2;
    }

    public void setPwd2(String pwd2) {
        this.pwd2 = pwd2;
    }

    public int getsizePosts() {
        return getOwner().getPosts().size();
    }

    public String createAccount() {
        try {
            if ((registerUser.getEmail().length() < 4) || !registerUser.getEmail().contains("@") || !registerUser.getEmail().contains(".")) {
                FacesMessage msg = new FacesMessage("Please enter a valid email");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            RegisterUser userAccount = ejbUserManager.findUserByEmail(registerUser.getEmail());
            if (userAccount != null) {
                if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                    FacesMessage msg = new FacesMessage("The User Account exist.");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("If you forgot your password or need to reactive your account click in the link to recovery password.");
                    msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    linkRPOk = true;
                    return null;
                }
                userAccount.setRegisterDate(new Date(System.currentTimeMillis()));
                Random r = new Random();
                String token = Long.toString(Math.abs(r.nextLong()), 36);
                userAccount.setConfirmationCode(token);
                ejbUserManager.update(userAccount, false);
                ejbEmail.sendAccountConfirmation(userAccount);
                FacesMessage msg = new FacesMessage("The user " + userAccount.getEmail() + " was registered correctly.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("Please active your account from email received.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                registerOk = true;
                return "success";
            }
            registerUser.setNumberOfPostings(10);
            registerUser.setRegisterDate(new Date(System.currentTimeMillis()));
            registerUser.setStatus("pending");
            Random r = new Random();
            String token = Long.toString(Math.abs(r.nextLong()), 36);
            registerUser.setConfirmationCode(token);
            ejbUserManager.create(registerUser);
            ejbEmail.sendAccountConfirmation(ejbUserManager.merge(registerUser));
            FacesMessage msg = new FacesMessage("The user " + registerUser.getEmail() + " was registered correctly.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            FacesMessage msg1 = new FacesMessage("Please active your account from email received.");
            FacesContext.getCurrentInstance().addMessage(null, msg1);
            registerOk = true;
            return "success";
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Ther user " + registerUser.getEmail() + " can't registration, maybe the email could not be sent or it doesn't exist");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public String confirmation() {
        try {
            if (!pwd1.equals(pwd2)) {
                FacesMessage msg = new FacesMessage("The passwords don't equals");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            RegisterUser user = (RegisterUser) SessionContext.getAttribute("user");
            user.setPassword(pwd1);
            user.setStatus("active");
            Random r = new Random();
            String token = Long.toString(Math.abs(r.nextLong()), 36);
            user.setConfirmationCode(token);
            ejbUserManager.update(user, true);
            FacesMessage msg = new FacesMessage("The user " + user.getEmail() + " has confimed account successfully.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            FacesMessage msg1 = new FacesMessage("Now you can access account with your new password");
            FacesContext.getCurrentInstance().addMessage(null, msg1);
            SessionContext.removeAttribute("user");
            confirmationOk = true;
            return "success";
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Can't confirm this user");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public String updateAccount() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
        HttpSession session = request.getSession();
        if (session.isNew()) {
            try {
                String errorPageURL = externalContext.getRequestContextPath() + "/faces/welcome.jsp";
                externalContext.redirect(errorPageURL);
                FacesMessage msg = new FacesMessage("The session has bean expired");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return null;
            }
        } else {
            try {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                RegisterUser owner = sessionBean.getEjbSession().getOwner();
                if (email1 == null) {
                    if (pwd != null) {
                        Encrypter e = new Encrypter();
                        String securePwd = e.encrypt(pwd);
                        if (!owner.getPassword().equals(securePwd)) {
                            FacesMessage msg = new FacesMessage("The password don't equal to actual password");
                            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            return null;
                        }
                        if (pwd1.equals("") || pwd2.equals("") || !pwd1.equals(pwd2)) {
                            FacesMessage msg = new FacesMessage("The news passwords don't equals or invalids");
                            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            return null;
                        }
                        owner.setPassword(pwd1);
                        //owner.setDefaultSite(ejbSiteManager.find(defaultSiteId));
                        owner.setNumberOfPostings(numberOfPostings);
                        ejbUserManager.update(owner, true);
                        FacesMessage msg = new FacesMessage("The user " + owner.getEmail() + " was edit correctly");
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        sessionBean.getEjbSession().setOwner(null);
                        sessionBean.setPagePostsUser(0);
                        return "success1";
                    } else {
                        //owner.setDefaultSite(ejbSiteManager.find(defaultSiteId));
                        owner.setNumberOfPostings(numberOfPostings);
                        ejbUserManager.update(owner, false);
                        sessionBean.getEjbSession().setOwner(owner);
                        FacesMessage msg = new FacesMessage("The user " + owner.getEmail() + " was edit correctly");
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return "success";
                    }
                } else {
                    if ((email1.length() < 4) || !email1.contains("@") || !email1.contains(".") || (email2.length() < 4) || !email2.contains("@") || !email2.contains(".") || !email1.equals(email2) || email1.equals(owner.getEmail())) {
                        FacesMessage msg = new FacesMessage("The news emails don't equals or invalids");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                        return null;
                    }
                    RegisterUser userAccount = ejbUserManager.findUserByEmail(email1);
                    if (userAccount != null) {
                        if (userAccount.getStatus().equals("active") || userAccount.getStatus().equals("reactive")) {
                            FacesMessage msg = new FacesMessage("The User Account associated a new email exist.");
                            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                            FacesContext.getCurrentInstance().addMessage(null, msg);
                            FacesMessage msg1 = new FacesMessage("If you forgot your password or need to reactive the other account clik in the link to recovery password.");
                            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                            FacesContext.getCurrentInstance().addMessage(null, msg1);
                            linkRPOk = true;
                            return null;
                        }
                        ejbUserManager.delete(userAccount);
                    }
                    owner.setEmail(email1);
                    owner.setStatus("reactive");
                    //owner.setDefaultSite(ejbSiteManager.find(defaultSiteId));
                    owner.setNumberOfPostings(numberOfPostings);
                    ejbUserManager.update(owner, false);
                    ejbEmail.sendAccountConfirmation(ejbUserManager.merge(owner));
                    FacesMessage msg = new FacesMessage("The user " + email1 + " was edit correctly.");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    FacesMessage msg1 = new FacesMessage("Please reactive your account from email received in your new email address .");
                    FacesContext.getCurrentInstance().addMessage(null, msg1);
                    sessionBean.getEjbSession().setOwner(null);
                    sessionBean.setPagePostsUser(0);
                    return "success1";
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                FacesMessage msg = new FacesMessage("Can't edit this user, maybe the email could not be sent or it doesn't exist");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
        }
    }

    public String recoveryPassword() {
        try {
            if ((emailSearch.length() < 4) || !emailSearch.contains("@") || !emailSearch.contains(".")) {
                FacesMessage msg = new FacesMessage("Please enter a valid email");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            RegisterUser identity = ejbUserManager.findUserByEmail(emailSearch);
            if (identity == null) {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "No such user, please try again", "The authentication failed please check the email and try again");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return null;
            }
            if (identity.getStatus().equals("active") || identity.getStatus().equals("reactive")) {
                ejbEmail.sendRecoveryConfirmation(identity);
                FacesMessage msg = new FacesMessage("The user " + emailSearch + " was recovered password correctly.");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesMessage msg1 = new FacesMessage("The recovery confirmation was sended to email address.");
                FacesContext.getCurrentInstance().addMessage(null, msg1);
                recoveryOk = true;
                return "success";
            }
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Your Account not active.", "The recovery password failed");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            FacesMessage msg1 = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please active your account from email recieved or sign up again.", "The recovery password failed");
            FacesContext.getCurrentInstance().addMessage(null, msg1);
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesMessage msg = new FacesMessage("Ther user " + emailSearch + " can't recoverd your password, maybe the email could not be sent or it doesn't exist");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return null;
        }
    }

    public long getDefaultSiteId() {
        if (defaultSiteId == 0 && getOwner().getDefaultSite() != null) {
            defaultSiteId = getOwner().getDefaultSite().getId();
        }
        return defaultSiteId;
    }

    public void setDefaultSiteId(long defaultSiteId) {
        this.defaultSiteId = defaultSiteId;
    }

    public boolean isRegisterOk() {
        return registerOk;
    }

    public void setRegisterOk(boolean registerOk) {
        this.registerOk = registerOk;
    }

    public String getEmailSearch() {
        return emailSearch;
    }

    public void setEmailSearch(String emailSearch) {
        this.emailSearch = emailSearch;
    }

    public boolean isRecoveryOk() {
        return recoveryOk;
    }

    public void setRecoveryOk(boolean recoveryOk) {
        this.recoveryOk = recoveryOk;
    }

    public boolean isConfirmationOk() {
        return confirmationOk;
    }

    public void setConfirmationOk(boolean confirmationOk) {
        this.confirmationOk = confirmationOk;
    }

    public boolean isLinkRPOk() {
        return linkRPOk;
    }

    public void setLinkRPOk(boolean linkRPOk) {
        this.linkRPOk = linkRPOk;
    }

    public String getEmail1() {
        return email1;
    }

    public void setEmail1(String email1) {
        this.email1 = email1;
    }

    public String getEmail2() {
        return email2;
    }

    public void setEmail2(String email2) {
        this.email2 = email2;
    }

    public long getSiteId() {
        if (siteId == 0) {
            if (getOwner().getDefaultSite() != null) {
                siteId = (long) getOwner().getDefaultSite().getId();
            } else {
                SessionBean sessionBean = (SessionBean) SessionContext.getAttribute("sessionBean");
                siteId = sessionBean.getEjbSession().getCurrentSite().getId();
            }
        }
        return siteId;
    }

    public void setSiteId(long siteId) {
        this.siteId = siteId;
    }

    public Site getPostingSite() {
        return ejbSiteManager.find(siteId);
    }

    public int getNumberOfPostings() {
        if (numberOfPostings == 0) {
            numberOfPostings = getOwner().getNumberOfPostings();
        }
        return numberOfPostings;
    }

    public void setNumberOfPostings(int numberOfPostings) {
        this.numberOfPostings = numberOfPostings;
    }

}